<template>
  <div class="exams-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h1>考试列表</h1>
        <p>查看和参加可用的考试</p>
      </div>
      <div class="header-right">
        <el-button @click="refreshExams" :icon="Refresh">
          刷新
        </el-button>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card available">
        <div class="stat-icon">
          <i class="fas fa-clipboard-list"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.available }}</h3>
          <p>可参加</p>
        </div>
      </div>
      
      <div class="stat-card in-progress">
        <div class="stat-icon">
          <i class="fas fa-play-circle"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.inProgress }}</h3>
          <p>进行中</p>
        </div>
      </div>
      
      <div class="stat-card completed">
        <div class="stat-icon">
          <i class="fas fa-check-circle"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.completed }}</h3>
          <p>已完成</p>
        </div>
      </div>
      
      <div class="stat-card missed">
        <div class="stat-icon">
          <i class="fas fa-times-circle"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.missed }}</h3>
          <p>已错过</p>
        </div>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-left">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索考试名称..."
          :prefix-icon="Search"
          clearable
          @input="handleSearch"
        />
        <el-select v-model="statusFilter" placeholder="考试状态" clearable>
          <el-option label="全部状态" value="" />
          <el-option label="可参加" value="available" />
          <el-option label="进行中" value="in-progress" />
          <el-option label="已完成" value="completed" />
          <el-option label="已错过" value="missed" />
        </el-select>
        <!-- 暂时注释科目筛选，后端数据中缺少科目字段
        <el-select v-model="subjectFilter" placeholder="科目" clearable>
          <el-option label="全部科目" value="" />
          <el-option label="数据结构" value="data-structure" />
          <el-option label="算法设计" value="algorithm" />
          <el-option label="计算机网络" value="network" />
          <el-option label="操作系统" value="os" />
        </el-select>
        -->
        <el-select v-model="sortBy" placeholder="排序方式">
          <el-option label="开始时间" value="startTime" />
          <el-option label="结束时间" value="endTime" />
          <el-option label="考试名称" value="name" />
          <el-option label="考试时长" value="duration" />
        </el-select>
      </div>
    </div>
    
    <!-- 考试列表 -->
    <div class="exams-grid">
      <div 
        v-for="exam in filteredExams" 
        :key="exam.id" 
        class="exam-card"
        :class="exam.status"
      >
        <div class="exam-header">
          <div class="exam-title">
            <h3>{{ exam.name }}</h3>
            <el-tag 
              :type="getStatusTagType(exam.status)"
              size="small"
            >
              {{ getStatusLabel(exam.status) }}
            </el-tag>
          </div>
          <div class="exam-time-badge">
            <i class="fas fa-clock"></i>
            <span>{{ exam.duration }} 分钟</span>
          </div>
        </div>
        
        <div class="exam-content">
          <div class="exam-description">
            <p>{{ exam.description }}</p>
          </div>
          
          <div class="exam-meta">
            <div class="meta-row">
              <div class="meta-item">
                <i class="fas fa-list"></i>
                <span>{{ exam.questionCount }} 题</span>
              </div>
              <div class="meta-item">
                <i class="fas fa-star"></i>
                <span>{{ exam.totalScore }} 分</span>
              </div>

              <div class="meta-item" v-if="exam.groupName">
                <i class="fas fa-graduation-cap"></i>
                <span>{{ exam.groupName }}</span>
              </div>
            </div>
            
            <div class="meta-row">
              <div class="meta-item">
                <i class="fas fa-calendar-alt"></i>
                <span>开始：{{ formatDateTime(exam.startTime) }}</span>
              </div>
            </div>
            
            <div class="meta-row">
              <div class="meta-item">
                <i class="fas fa-calendar-times"></i>
                <span>结束：{{ formatDateTime(exam.endTime) }}</span>
              </div>
            </div>
          </div>
          
          <!-- 暂时注释科目显示，后端数据中缺少科目字段
          <div class="exam-subjects">
            <el-tag 
              v-for="subject in exam.subjects" 
              :key="subject" 
              size="small"
              class="subject-tag"
            >
              {{ getSubjectLabel(subject) }}
            </el-tag>
          </div>
          -->
          
          <!-- 考试进度 -->
          <div v-if="exam.progress" class="exam-progress">
            <div class="progress-header">
              <span class="progress-label">答题进度</span>
              <span class="progress-text">{{ exam.progress.answered }} / {{ exam.questionCount }}</span>
            </div>
            <el-progress 
              :percentage="getProgressPercentage(exam)"
              :stroke-width="8"
              :show-text="false"
            />
            <div class="progress-footer">
              <span class="time-used">已用时：{{ formatDuration(exam.progress.timeUsed) }}</span>
              <span class="time-remaining">剩余：{{ getTimeRemaining(exam) }}</span>
            </div>
          </div>
          
          <!-- 考试结果 -->
          <div v-if="exam.result" class="exam-result">
            <div class="result-score">
              <span class="score-label">得分：</span>
              <span class="score-value" :class="getScoreClass(exam.result.score, exam.totalScore)">
                {{ exam.result.score }} / {{ exam.totalScore }}
              </span>
              <span class="score-percentage">
                ({{ getScorePercentage(exam.result.score, exam.totalScore) }}%)
              </span>
            </div>
            <div class="result-meta">
              <span class="submit-time">
                <i class="fas fa-calendar-check"></i>
                提交时间：{{ formatDateTime(exam.result.submitTime) }}
              </span>
              <span class="exam-duration">
                <i class="fas fa-stopwatch"></i>
                用时：{{ formatDuration(exam.result.duration) }}
              </span>
            </div>
          </div>
          
          <!-- 倒计时 -->
          <div v-if="exam.status === 'available' && isExamSoon(exam)" class="exam-countdown">
            <div class="countdown-label">
              <i class="fas fa-hourglass-half"></i>
              距离开始还有：
            </div>
            <div class="countdown-time">
              {{ getCountdown(exam.startTime) }}
            </div>
          </div>
          
          <div v-if="exam.status === 'in-progress'" class="exam-countdown">
            <div class="countdown-label">
              <i class="fas fa-hourglass-end"></i>
              距离结束还有：
            </div>
            <div class="countdown-time">
              {{ getCountdown(exam.endTime) }}
            </div>
          </div>
        </div>
        
        <div class="exam-footer">
          <div class="exam-actions">
            <el-button 
              v-if="getExamButtonText(exam) === '未开始'"
              disabled
              size="small"
            >
              未开始
            </el-button>
            
            <el-button 
              v-else-if="getExamButtonText(exam) === '开始考试'"
              type="primary" 
              size="small"
              @click="startExam(exam)"
            >
              开始考试
            </el-button>
            
            <el-button 
              v-else-if="getExamButtonText(exam) === '恢复考试'"
              type="success" 
              size="small"
              @click="startExam(exam)"
            >
              恢复考试
            </el-button>
            
            <el-button 
              v-else-if="getExamButtonText(exam) === '已提交'"
              size="small"
              @click="viewResult(exam)"
            >
              查看结果
            </el-button>
            
            <el-button 
              v-else-if="getExamButtonText(exam) === '已错过' || getExamButtonText(exam) === '已中断'"
              disabled
              size="small"
            >
              {{ getExamButtonText(exam) }}
            </el-button>
            
            <el-button 
              size="small"
              @click="viewExamDetails(exam)"
            >
              查看详情
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 48]"
        :total="totalExams"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 空状态 -->
    <div v-if="filteredExams.length === 0" class="empty-state">
      <i class="fas fa-clipboard-list"></i>
      <h3>暂无考试</h3>
      <p>当前筛选条件下没有找到考试</p>
    </div>
    
    <!-- 考试详情对话框 -->
    <el-dialog
      v-model="showDetailsDialog"
      :title="selectedExam?.name"
      width="700px"
    >
      <div v-if="selectedExam" class="exam-details">
        <div class="details-section">
          <h4>考试信息</h4>
          <div class="details-grid">
            <div class="detail-item">
              <span class="label">考试时长：</span>
              <span class="value">{{ selectedExam.duration }} 分钟</span>
            </div>
            <div class="detail-item">
              <span class="label">题目数量：</span>
              <span class="value">{{ selectedExam.questionCount }} 题</span>
            </div>
            <div class="detail-item">
              <span class="label">总分：</span>
              <span class="value">{{ selectedExam.totalScore }} 分</span>
            </div>
            <div class="detail-item">
              <span class="label">开始时间：</span>
              <span class="value">{{ formatDateTime(selectedExam.startTime) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">结束时间：</span>
              <span class="value">{{ formatDateTime(selectedExam.endTime) }}</span>
            </div>

          </div>
        </div>
        
        <div class="details-section">
          <h4>考试说明</h4>
          <div class="exam-description">
            <p>{{ selectedExam.description }}</p>
          </div>
        </div>
        
        <div class="details-section">
          <h4>考试规则</h4>
          <div class="exam-rules">
            <ul>
              <li>考试开始后不能暂停，请确保网络稳定</li>
              <li>考试过程中不允许切换浏览器标签页</li>
              <li>考试时间到后系统将自动提交答案</li>
              <li>每道题目都有时间限制，请合理分配时间</li>
              <li>提交后不能修改答案，请仔细检查</li>
            </ul>
          </div>
        </div>
        
        <div v-if="selectedExam.questionTypes" class="details-section">
          <h4>题型分布</h4>
          <div class="question-types">
            <div 
              v-for="type in selectedExam.questionTypes" 
              :key="type.type" 
              class="type-item"
            >
              <el-tag :type="getQuestionTypeTag(type.type)" size="small">
                {{ getQuestionTypeLabel(type.type) }}
              </el-tag>
              <span class="type-count">{{ type.count }} 题</span>
              <span class="type-score">{{ type.totalScore }} 分</span>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showDetailsDialog = false">关闭</el-button>
        <el-button 
          v-if="selectedExam?.status === 'available' && isExamStarted(selectedExam)"
          type="primary" 
          @click="startExamFromDialog"
        >
          开始考试
        </el-button>
        <el-button 
          v-else-if="selectedExam?.status === 'in-progress'"
          type="success" 
          @click="continueExamFromDialog"
        >
          继续考试
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getMyExamAssignments } from '@/api/exam/examAssignments'
import { startExamSession, getExamSessions, getExamSessionByExamAndStudent, resumeExamSession } from '@/api/exam/examSessions'
import { useAppStore } from '@/stores'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const appStore = useAppStore()
const userStore = useUserStore()
const searchKeyword = ref('')
const statusFilter = ref('')
const subjectFilter = ref('')
const sortBy = ref('startTime')
const currentPage = ref(1)
const pageSize = ref(12)
const totalExams = ref(0)
const showDetailsDialog = ref(false)
const selectedExam = ref(null)
const countdownTimer = ref(null)
const loading = ref(false)

const stats = ref({
  available: 0,
  inProgress: 0,
  completed: 0,
  missed: 0
})

const exams = ref([])
const examSessions = ref({}) // 存储考试会话信息，key为assignmentId

// 过滤和排序后的所有考试数据
const allFilteredExams = computed(() => {
  let result = exams.value
  
  if (searchKeyword.value) {
    result = result.filter(e => 
      e.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  
  if (statusFilter.value) {
    result = result.filter(e => e.status === statusFilter.value)
  }
  
  // 暂时注释科目筛选，后端数据中缺少科目字段
  // if (subjectFilter.value) {
  //   result = result.filter(e => e.subjects.includes(subjectFilter.value))
  // }
  
  // 排序
  result.sort((a, b) => {
    switch (sortBy.value) {
      case 'startTime':
        return new Date(a.startTime) - new Date(b.startTime)
      case 'endTime':
        return new Date(a.endTime) - new Date(b.endTime)
      case 'name':
        return a.name.localeCompare(b.name)
      case 'duration':
        return b.duration - a.duration
      default:
        return 0
    }
  })
  
  return result
})

// 当前页显示的考试数据（分页后）
const filteredExams = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allFilteredExams.value.slice(start, end)
})

const getStatusLabel = (status) => {
  const labels = {
    available: '可参加',
    'in-progress': '进行中',
    completed: '已完成',
    missed: '已错过'
  }
  return labels[status] || status
}

const getStatusTagType = (status) => {
  const types = {
    available: 'primary',
    'in-progress': 'success',
    completed: 'info',
    missed: 'danger'
  }
  return types[status] || 'info'
}

const getSubjectLabel = (subject) => {
  const labels = {
    'data-structure': '数据结构',
    'algorithm': '算法设计',
    'network': '计算机网络',
    'os': '操作系统',
    'database': '数据库'
  }
  return labels[subject] || subject
}

const getQuestionTypeLabel = (type) => {
  const labels = {
    single: '单选题',
    multiple: '多选题',
    boolean: '判断题',
    fill: '填空题',
    essay: '简答题'
  }
  return labels[type] || type
}

const getQuestionTypeTag = (type) => {
  const types = {
    single: 'primary',
    multiple: 'success',
    boolean: 'warning',
    fill: 'info',
    essay: 'danger'
  }
  return types[type] || 'primary'
}

const getProgressPercentage = (exam) => {
  if (!exam.progress || !exam.questionCount || exam.progress.answered == null) return 0
  const percentage = Math.round((exam.progress.answered / exam.questionCount) * 100)
  return isNaN(percentage) ? 0 : percentage
}

const getScorePercentage = (score, totalScore) => {
  if (score == null || totalScore == null || totalScore === 0) return 0
  const percentage = Math.round((score / totalScore) * 100)
  return isNaN(percentage) ? 0 : percentage
}

const getScoreClass = (score, totalScore) => {
  const percentage = (score / totalScore) * 100
  if (percentage >= 90) return 'excellent'
  if (percentage >= 80) return 'good'
  if (percentage >= 70) return 'average'
  return 'poor'
}

const isExamStarted = (exam) => {
  return currentTime.value >= new Date(exam.startTime)
}

const isExamSoon = (exam) => {
  const now = currentTime.value
  const startTime = new Date(exam.startTime)
  const timeDiff = startTime - now
  return timeDiff > 0 && timeDiff <= 24 * 60 * 60 * 1000 // 24小时内
}

const getCountdown = (targetTime) => {
  // 使用响应式的currentTime来确保倒计时实时更新
  const now = currentTime.value
  const target = new Date(targetTime)
  const diff = target - now
  
  if (diff <= 0) return '已结束'
  
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((diff % (1000 * 60)) / 1000)
  
  if (days > 0) {
    return `${days}天 ${hours}小时 ${minutes}分钟`
  } else if (hours > 0) {
    return `${hours}小时 ${minutes}分钟 ${seconds}秒`
  } else {
    return `${minutes}分钟 ${seconds}秒`
  }
}

const getTimeRemaining = (exam) => {
  if (!exam.progress) return ''
  const remainingTime = exam.duration * 60 - exam.progress.timeUsed
  return formatDuration(remainingTime)
}

const formatDateTime = (dateTime) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

const formatDuration = (seconds) => {
  if (seconds <= 0) return '0分钟'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  }
  return `${minutes}分钟`
}

const refreshExams = async () => {
  try {
    loading.value = true
    appStore.setLoading(true)
    
    const response = await getMyExamAssignments()
    
    if (response && response.code === 200 && response.data) {
      // 处理后端返回的数据结构
      const examData = Array.isArray(response.data) ? response.data : []
      
      // 转换后端数据格式为前端需要的格式
      exams.value = examData
        .filter(assignment => assignment && assignment.exam) // 过滤掉空的assignment或exam
        .map(assignment => {
        const exam = assignment.exam
        return {
          id: exam.examId,
          name: exam.title,
          description: exam.description || '',
          status: determineExamStatus(assignment),
          subjects: ['综合考试'], // 使用通用科目，实际应从后端获取
          duration: exam.durationMinutes || 0,
          questionCount: exam.questions ? exam.questions.length : Math.max(1, Math.floor((exam.durationMinutes || 60) / 3)),
          totalScore: exam.totalScore || (exam.questions ? calculateTotalScore(exam.questions) : Math.max(1, Math.floor((exam.durationMinutes || 60) / 3)) * 10),
          participantCount: Math.floor(Math.random() * 50) + 10, // 模拟参与人数，实际应从后端获取
          startTime: assignment.startTime, // 使用assignment的开始时间
          endTime: assignment.endTime, // 使用assignment的结束时间
          assignmentId: assignment.assignmentId,
          progress: null, // 需要从其他接口获取
          result: null, // 需要从其他接口获取
          questionTypes: getQuestionTypesFromQuestions(exam.questions || []),
          groupName: assignment.groupName || '', // 添加班级信息
          examStartTime: exam.startTime, // 保留考试原始开始时间
          examEndTime: exam.endTime, // 保留考试原始结束时间
          courseId: exam.courseId // 添加课程ID
        }
      })
      
      // 获取学生的考试会话信息
      await loadExamSessions()
      
      // 根据会话信息更新考试状态
      updateExamStatusWithSessions()
      
      totalExams.value = exams.value.length
      
      // 更新统计信息
      updateStats()
      
      ElMessage.success('刷新成功')
    } else {
      throw new Error(response?.message || '获取考试列表失败')
    }
  } catch (error) {
    console.error('加载考试列表失败:', error)
    // 屏蔽考试会话不存在的调试信息，不显示给用户
    // if (!error.message || !error.message.includes('考试会话不存在')) {
    //   ElMessage.error('加载考试列表失败: ' + (error.message || '请求失败'))
    // }
  } finally {
    loading.value = false
    appStore.setLoading(false)
  }
}

// 根据时间判断考试状态
const determineExamStatus = (assignment) => {
  const now = currentTime.value
  const startTime = new Date(assignment.startTime)
  const endTime = new Date(assignment.endTime)
  
  if (now < startTime) {
    return 'available'
  } else if (now >= startTime && now <= endTime) {
    return 'in-progress'
  } else {
    return 'missed'
  }
}

// 计算总分
const calculateTotalScore = (questions) => {
  // 如果questions为null或undefined，返回0
  if (!questions || !Array.isArray(questions)) {
    return 0
  }
  // 简单计算，每题10分，实际应该从题目配置中获取
  return questions.length * 10
}

// 从题目列表中提取题型信息
const getQuestionTypesFromQuestions = (questions) => {
  // 如果questions为null或undefined，返回空数组
  if (!questions || !Array.isArray(questions)) {
    return []
  }
  
  const typeMap = {}
  questions.forEach(q => {
    const type = q.question.questionType
    if (!typeMap[type]) {
      typeMap[type] = { type, count: 0, totalScore: 0 }
    }
    typeMap[type].count++
    typeMap[type].totalScore += 10 // 简单计算，每题10分
  })
  return Object.values(typeMap)
}

// 加载学生的考试会话信息
const loadExamSessions = async () => {
  try {
    examSessions.value = {}
    
    // 为每个考试单独获取会话信息
    const sessionPromises = exams.value.map(async (exam) => {
      try {
        const response = await getExamSessionByExamAndStudent(exam.id)
        // console.log(`获取考试${exam.id}的会话信息:`, response)
        
        if (response && response.code === 200 && response.data) {
          examSessions.value[exam.id] = response.data
        }
      } catch (error) {
          // 区分不同类型的错误
        if (error.response?.status === 404 || 
            error.response?.status === 500 ||
            error.message?.includes('不存在') || 
            error.message?.includes('未找到') ||
            error.message?.includes('考试会话不存在') ||
            error.message?.includes('没有安排给') ||
            error.message?.includes('未安排')) {
          // 404、500或明确表示不存在/未安排的错误是正常的，表示该考试没有会话记录或未安排给该考生
          // 使用debug级别的日志，避免在控制台显示误导性信息
          console.debug(`考试${exam.id}暂无会话记录`)
        } else {
          // 其他错误可能是系统问题，需要记录但不中断流程
          console.warn(`获取考试${exam.id}会话信息失败:`, error.message)
        }
        }
    })
    
    await Promise.all(sessionPromises)
    // console.log('Final examSessions:', examSessions.value)
  } catch (error) {
    // console.warn('获取考试会话失败:', error)
  }
}

// getCurrentUserId方法已删除，API已更新为自动获取当前用户

// 根据会话信息更新考试状态
const updateExamStatusWithSessions = () => {
  exams.value.forEach(exam => {
    const session = examSessions.value[exam.id]
    const now = currentTime.value
    const startTime = new Date(exam.startTime)
    const endTime = new Date(exam.endTime)
    const isInExamTime = now >= startTime && now <= endTime
    
    if (session) {
      // 有会话记录，根据数据库枚举状态判断
      if (session.status === 'submitted') {
        // 已提交状态
        exam.status = 'completed'
        exam.result = {
          score: session.score || 0,
          submitTime: session.endTime,
          duration: session.duration || 0
        }
      } else if (session.status === 'started' && isInExamTime) {
        // 已开始且在考试时间内 - 恢复考试
        exam.status = 'in-progress'
        exam.progress = {
          answered: session.answers ? session.answers.filter(a => !a.isDraft).length : 0,
          timeUsed: session.remainingTime ? (exam.duration * 60 - session.remainingTime) : 0
        }
      } else if (session.status === 'interrupted') {
        // 考试被老师删掉/中断
        exam.status = 'missed'
      } else if (session.status === 'started' && now > endTime) {
        // 已开始但超时，标记为错过
        exam.status = 'missed'
      } else {
        // 其他情况，根据时间判断
        if (now < startTime) {
          exam.status = 'available'
        } else if (now > endTime) {
          exam.status = 'missed'
        } else {
          exam.status = 'available' // 在考试时间内
        }
      }
    } else {
      // 无会话记录，根据时间判断
      if (now < startTime) {
        exam.status = 'available' // 未开始
      } else if (now > endTime) {
        exam.status = 'missed' // 已错过
      } else {
        exam.status = 'available' // 在考试时间内但未开始 - 开始考试
      }
    }
  })
}

const updateStats = () => {
  stats.value = {
    available: 0,
    inProgress: 0,
    completed: 0,
    missed: 0
  }
  
  exams.value.forEach(exam => {
    if (exam.status === 'completed') {
      stats.value.completed++
    } else if (exam.status === 'in-progress') {
      stats.value.inProgress++
    } else if (exam.status === 'available') {
      stats.value.available++
    } else if (exam.status === 'missed') {
      stats.value.missed++
    }
  })
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleSizeChange = (size) => {
  pageSize.value = size
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const startExam = async (exam) => {
  try {
    const session = examSessions.value[exam.id]
    const now = currentTime.value
    const endTime = new Date(exam.endTime)
    const isResume = session && session.status === 'started' && now <= endTime
    
    await ElMessageBox.confirm(
      `确定要${isResume ? '恢复' : '开始'}「${exam.name}」考试吗？\n\n考试时长：${exam.duration} 分钟\n题目数量：${exam.questionCount} 题\n\n${isResume ? '将恢复之前的答题进度' : '开始后不能暂停，请确保网络稳定'}。`,
      `确认${isResume ? '恢复' : '开始'}考试`,
      {
        confirmButtonText: isResume ? '恢复考试' : '开始考试',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )
    
    let sessionId;
    
    
    if (isResume) {
      // 继续考试，调用resumeExamSession
      const resumeData = {
        sessionId: parseInt(session.sessionId), // 确保sessionId是数字类型
        ipAddress: await getClientIP(),
        deviceInfo: getDeviceInfoString()
      }
      
      console.log('Resume exam data:', resumeData) // 添加调试信息
      
      try {
        const response = await resumeExamSession(resumeData)
        if (response && response.code === 200 && response.data) {
          sessionId = response.data.sessionId
        } else {
          console.error('Resume exam failed:', response) // 添加错误调试信息
          throw new Error(response?.message || '恢复考试会话失败')
        }
      } catch (resumeError) {
        // 检查是否是Redis草稿获取失败的错误
        if (resumeError.message && resumeError.message.includes('从 Redis 获取草稿失败')) {
          // 显示黄色警告，但继续进入考试
          ElMessage.warning('未找到之前的答题记录，将开始新的考试')
          
          // 开始新考试，创建新会话
          const startData = {
            assignmentId: exam.assignmentId,
            ipAddress: await getClientIP(),
            deviceInfo: getDeviceInfoString(),
            videoStreamUrl: ""
          }
          
          const newResponse = await startExamSession(startData)
          
          if (newResponse && newResponse.code === 200 && newResponse.data) {
            sessionId = newResponse.data
          } else {
            throw new Error(newResponse?.message || '创建考试会话失败')
          }
        } else if (resumeError.message && resumeError.message.includes('考试会话已存在')) {
          // 会话已存在，直接使用现有的sessionId
          ElMessage.info('检测到现有考试会话，将继续使用')
          sessionId = session.sessionId
        } else {
          // 其他错误，正常抛出
          throw resumeError
        }
      }
    } else {
      // 开始新考试，创建新会话
      const startData = {
        assignmentId: exam.assignmentId,
        ipAddress: await getClientIP(),
        deviceInfo: getDeviceInfoString(),
        videoStreamUrl: ""
      }
      
      try {
        const response = await startExamSession(startData)
        
        if (response && response.code === 200 && response.data) {
          sessionId = response.data
        } else {
          throw new Error(response?.message || '创建考试会话失败')
        }
      } catch (startError) {
        // 检查是否是考试会话已存在的错误
        if (startError.message && startError.message.includes('考试会话已存在')) {
          // 会话已存在，尝试获取现有会话并使用
          ElMessage.info('检测到现有考试会话，将继续使用')
          const existingSession = examSessions.value[exam.id]
          if (existingSession && existingSession.sessionId) {
            sessionId = existingSession.sessionId
          } else {
            throw new Error('无法获取现有考试会话信息，请刷新页面重试')
          }
        } else {
          // 其他错误，正常抛出
          throw startError
        }
      }
    }
    
    // 跳转到考试页面
    router.push({
      path: `/student/exam/${exam.id}`,
      query: {
        sessionId: sessionId
      }
    })
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('开始考试失败:', error)
      ElMessage.error('开始考试失败：' + (error.message || '请重试'))
    }
  }
}

// 获取客户端IP（简化版）
const getClientIP = async () => {
  try {
    // 这里可以调用第三方服务获取IP，或者让后端处理
    return '127.0.0.1' // 临时返回本地IP
  } catch (error) {
    return '127.0.0.1'
  }
}

// 获取设备信息字符串
const getDeviceInfoString = () => {
  const browser = getBrowserInfo()
  const os = getOSInfo()
  return `${browser}/${os}`
}

// 获取浏览器信息
const getBrowserInfo = () => {
  const userAgent = navigator.userAgent
  if (userAgent.includes('Chrome')) return 'Chrome'
  if (userAgent.includes('Firefox')) return 'Firefox'
  if (userAgent.includes('Safari')) return 'Safari'
  if (userAgent.includes('Edge')) return 'Edge'
  return 'Unknown'
}

// 获取操作系统信息
const getOSInfo = () => {
  const platform = navigator.platform
  const userAgent = navigator.userAgent
  if (platform.includes('Win')) return 'Windows'
  if (platform.includes('Mac')) return 'macOS'
  if (platform.includes('Linux')) return 'Linux'
  if (userAgent.includes('Android')) return 'Android'
  if (userAgent.includes('iPhone') || userAgent.includes('iPad')) return 'iOS'
  return 'Unknown'
}

// 获取考试按钮文本
const getExamButtonText = (exam) => {
  const session = examSessions.value[exam.id]
  const now = currentTime.value
  const startTime = new Date(exam.startTime)
  const endTime = new Date(exam.endTime)
  const isInExamTime = now >= startTime && now <= endTime
  
  // console.log('getExamButtonText - exam.id:', exam.id, 'session:', session, 'status:', session?.status)
  
  if (session) {
    if (session.status === 'submitted') {
      return '已提交'
    } else if (session.status === 'started' && isInExamTime) {
      return '恢复考试'
    } else if (session.status === 'interrupted') {
      return '已中断'
    } else if (session.status === 'started' && now > endTime) {
      return '已错过'
    }
  }
  
  // 无会话或其他状态
  if (now < startTime) {
    return '未开始'
  } else if (now > endTime) {
    return '已错过'
  } else {
    return '开始考试'
  }
}

// continueExam方法已删除，统一使用startExam方法

const viewResult = (exam) => {
  router.push(`/student/result/${exam.id}`)
}

const viewExamDetails = (exam) => {
  selectedExam.value = exam
  showDetailsDialog.value = true
}

const startExamFromDialog = () => {
  showDetailsDialog.value = false
  startExam(selectedExam.value)
}

const continueExamFromDialog = () => {
  showDetailsDialog.value = false
  startExam(selectedExam.value)
}

// 添加一个响应式变量来触发倒计时更新
const currentTime = ref(new Date())

const startCountdownTimer = () => {
  countdownTimer.value = setInterval(() => {
    // 更新当前时间，触发倒计时重新计算
    currentTime.value = new Date()
  }, 1000)
}

const stopCountdownTimer = () => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
    countdownTimer.value = null
  }
}

// 监听过滤条件变化，更新总数和重置页码
watch([allFilteredExams, searchKeyword, statusFilter], () => {
  totalExams.value = allFilteredExams.value.length
  currentPage.value = 1 // 重置到第一页
})

onMounted(() => {
  startCountdownTimer()
  refreshExams()
})

onUnmounted(() => {
  stopCountdownTimer()
})
</script>

<style lang="scss" scoped>
.exams-page {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 32px;
  
  .header-left {
    h1 {
      font-size: 28px;
      font-weight: 700;
      color: var(--neutral-700);
      margin-bottom: 8px;
    }
    
    p {
      color: var(--neutral-500);
      font-size: 16px;
    }
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 16px;
  
  .stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    
    i {
      font-size: 20px;
      color: white;
    }
  }
  
  &.available .stat-icon {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  }
  
  &.in-progress .stat-icon {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  }
  
  &.completed .stat-icon {
    background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
  }
  
  &.missed .stat-icon {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  }
  
  .stat-content {
    h3 {
      font-size: 24px;
      font-weight: 700;
      color: var(--neutral-700);
      margin-bottom: 4px;
    }
    
    p {
      color: var(--neutral-500);
      font-size: 14px;
    }
  }
}

.search-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;
  
  .search-left {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
    
    .el-input {
      width: 250px;
    }
    
    .el-select {
      width: 150px;
    }
  }
}

.exams-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.exam-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  
  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
    transform: translateY(-2px);
  }
  
  &.available {
    border-left: 4px solid #3b82f6;
  }
  
  &.in-progress {
    border-left: 4px solid #10b981;
  }
  
  &.completed {
    border-left: 4px solid #8b5cf6;
  }
  
  &.missed {
    border-left: 4px solid #ef4444;
  }
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  
  .exam-title {
    flex: 1;
    
    h3 {
      font-size: 18px;
      font-weight: 600;
      color: var(--neutral-700);
      margin-bottom: 8px;
      line-height: 1.4;
    }
  }
  
  .exam-time-badge {
    display: flex;
    align-items: center;
    gap: 4px;
    background: var(--neutral-100);
    padding: 4px 8px;
    border-radius: 6px;
    font-size: 12px;
    color: var(--neutral-600);
    margin-left: 12px;
  }
}

.exam-content {
  flex: 1;
  
  .exam-description {
    margin-bottom: 16px;
    
    p {
      color: var(--neutral-600);
      font-size: 14px;
      line-height: 1.6;
    }
  }
  
  .exam-meta {
    margin-bottom: 16px;
    
    .meta-row {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      margin-bottom: 8px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .meta-item {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 13px;
        color: var(--neutral-500);
        
        i {
          color: var(--neutral-400);
          width: 12px;
        }
      }
    }
  }
  
  .exam-subjects {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-bottom: 16px;
    
    .subject-tag {
      font-size: 11px;
    }
  }
  
  .exam-progress {
    background: var(--neutral-50);
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 16px;
    
    .progress-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;
      
      .progress-label {
        font-size: 13px;
        font-weight: 600;
        color: var(--neutral-600);
      }
      
      .progress-text {
        font-size: 13px;
        color: var(--neutral-600);
      }
    }
    
    .progress-footer {
      display: flex;
      justify-content: space-between;
      margin-top: 8px;
      font-size: 12px;
      color: var(--neutral-500);
    }
  }
  
  .exam-result {
    background: var(--neutral-50);
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 16px;
    
    .result-score {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;
      
      .score-label {
        font-size: 14px;
        color: var(--neutral-600);
      }
      
      .score-value {
        font-size: 18px;
        font-weight: 700;
        
        &.excellent {
          color: #10b981;
        }
        
        &.good {
          color: #3b82f6;
        }
        
        &.average {
          color: #f59e0b;
        }
        
        &.poor {
          color: #ef4444;
        }
      }
      
      .score-percentage {
        font-size: 14px;
        color: var(--neutral-500);
      }
    }
    
    .result-meta {
      display: flex;
      flex-direction: column;
      gap: 4px;
      font-size: 12px;
      color: var(--neutral-500);
      
      span {
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }
  }
  
  .exam-countdown {
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 16px;
    text-align: center;
    
    .countdown-label {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      font-size: 13px;
      color: #92400e;
      margin-bottom: 4px;
    }
    
    .countdown-time {
      font-size: 16px;
      font-weight: 700;
      color: #92400e;
    }
  }
}

.exam-footer {
  .exam-actions {
    display: flex;
    gap: 8px;
    justify-content: flex-end;
  }
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  
  i {
    font-size: 64px;
    color: var(--neutral-300);
    margin-bottom: 24px;
  }
  
  h3 {
    font-size: 20px;
    color: var(--neutral-500);
    margin-bottom: 12px;
  }
  
  p {
    color: var(--neutral-400);
  }
}

.exam-details {
  .details-section {
    margin-bottom: 24px;
    
    h4 {
      font-size: 16px;
      font-weight: 600;
      color: var(--neutral-700);
      margin-bottom: 12px;
      padding-bottom: 8px;
      border-bottom: 1px solid var(--neutral-200);
    }
    
    .details-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 12px;
      
      .detail-item {
        display: flex;
        justify-content: space-between;
        
        .label {
          color: var(--neutral-500);
          font-size: 14px;
        }
        
        .value {
          color: var(--neutral-700);
          font-weight: 500;
          font-size: 14px;
        }
      }
    }
    
    .exam-description {
      p {
        color: var(--neutral-600);
        line-height: 1.6;
        font-size: 14px;
      }
    }
    
    .exam-rules {
      ul {
        color: var(--neutral-600);
        font-size: 14px;
        line-height: 1.6;
        padding-left: 20px;
        
        li {
          margin-bottom: 8px;
        }
      }
    }
    
    .question-types {
      display: flex;
      flex-direction: column;
      gap: 8px;
      
      .type-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 8px 12px;
        background: var(--neutral-50);
        border-radius: 6px;
        
        .type-count,
        .type-score {
          font-size: 13px;
          color: var(--neutral-600);
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .search-section {
    .search-left {
      flex-direction: column;
      
      .el-input,
      .el-select {
        width: 100%;
      }
    }
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .exams-grid {
    grid-template-columns: 1fr;
  }
  
  .exam-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
    
    .exam-time-badge {
      align-self: flex-start;
      margin-left: 0;
    }
  }
  
  .exam-meta {
    .meta-row {
      flex-direction: column;
      gap: 8px;
    }
  }
  
  .exam-actions {
    flex-direction: column;
    
    .el-button {
      width: 100%;
    }
  }
  
  .details-grid {
    grid-template-columns: 1fr;
  }
}
</style>